package com.cz.kingdee.prod;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONUtil;
import com.cz.kingdee.KingdeeClient;
import com.cz.kingdee.dto.*;
import com.kingdee.bos.webapi.entity.QueryParam;
import com.kingdee.bos.webapi.sdk.K3CloudApi;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 补偿生产汇报单
 */
public class PuChangMoPrd {
    public static void main(String[] args) throws Exception {
        KingdeeClient client = new KingdeeClient();
        //K3CloudApi k3CloudApi = client.getTestKingdeeClient();
        K3CloudApi k3CloudApi = client.getProdKingdeeClient();
        String dbGroup = "mes-prod-slave";

        QueryParam queryParam = new QueryParam();
        queryParam.setFormId("PRD_MO");
        queryParam.setFieldKeys("FBillNo,FStatus,FTreeEntity_FEntryId,FTreeEntity_FSeq,FDetailMaterialId");

        String mocNo = "MOCZ2501170011";
        String date = "2025-01-31 00:00:00";
        queryParam.setFilterString("FBillNo='"+mocNo+"'");

        List<PrdMo> prdMoList = k3CloudApi.executeBillQuery(queryParam, PrdMo.class);
        if(CollUtil.isNotEmpty(prdMoList)){
            for(PrdMo prdMo : prdMoList){
                int mocEntryId = prdMo.getFTreeEntity_FEntryId();

                /** 查询生产用料清单  **/
                QueryParam materialQueryParam = new QueryParam();
                materialQueryParam.setFormId("PRD_PPBOM");
                materialQueryParam.setFieldKeys("FBillNo");
                materialQueryParam.setFilterString("FMOEntryID ="+mocEntryId);
                List<PrdPpbom> prdPpbomList = k3CloudApi.executeBillQuery(materialQueryParam, PrdPpbom.class);
                String pBom = prdPpbomList.get(0).getFBillNo();
                System.out.println("物料编码：" + pBom);
                if(pBom.endsWith("-1")){
                    pBom = pBom.substring(0,pBom.length()-2);
                }


                QueryParam queryProMORPT = new QueryParam();
                queryProMORPT.setFormId("PRD_MORPT");
                queryProMORPT.setFieldKeys("FBillNo");
                queryProMORPT.setFilterString("FMoEntryId ="+mocEntryId);
                List<PrdMorpt> prdMorptList = k3CloudApi.executeBillQuery(queryProMORPT, PrdMorpt.class);
                /** 已经存在汇报单子 忽略  **/
                if(CollUtil.isNotEmpty(prdMorptList)){
                    continue;
                }
                /** 下推  **/
                PushPrdMorpt pushPrdMorpt = new PushPrdMorpt();
                pushPrdMorpt.setEntryIds(String.valueOf(mocEntryId));
                pushPrdMorpt.setTargetFormId("PRD_MORPT");
                pushPrdMorpt.setIsEnableDefaultRule(true);

                String result = k3CloudApi.push("PRD_MO", JSONUtil.toJsonStr(pushPrdMorpt));
                System.out.println(result);
                ResultWrapper resultWrapper = JSONUtil.toBean(result, ResultWrapper.class);
                int id = resultWrapper.getResult()
                        .getResponseStatus()
                        .getSuccessEntitys()
                        .get(0)
                        .getId();

                int fEntityId = resultWrapper.getResult()
                        .getResponseStatus()
                        .getSuccessEntitys()
                        .get(0)
                        .getEntryIds()
                        .getFEntity().get(0);

                /** 查询生产入库单子 **/
                QueryParam prdInStockQueryParam = new QueryParam();
                prdInStockQueryParam.setFormId("PRD_INSTOCK");
                prdInStockQueryParam.setFieldKeys("FRealQty");
                prdInStockQueryParam.setFilterString("FMoEntryId = "+mocEntryId);
                List<PrdInstock> prdInstockList = k3CloudApi.executeBillQuery(prdInStockQueryParam, PrdInstock.class);
                /** 没有入库单 忽略  **/
                if(CollUtil.isEmpty(prdInstockList)){
                    continue;
                }else {
                    int totalQuantity = prdInstockList.stream().mapToInt(PrdInstock::getFRealQty).sum();

                    String sql=" select abc.*,\n" +
                            "               tp.to_make_num                                 as jiaGongCount,\n" +
                            "               tp.only_code,\n" +
                            "               if(LEFT(tp.moc_no,4) = 'MOCZ',tp.moc_no, null) as production_order,\n" +
                            "               product_no,\n" +
                            "               tp.create_on,\n" +
                            "               p_bom_no\n" +
                            "        from (select SUM(CAST(total_time-prep_time as DECIMAL(12, 2)))                         as totalTime,\n" +
                            "                     ROUND(SUM(CAST(total_time-prep_time as DECIMAL(12, 2))) / process_num, 2) as singleJiaGongCount,\n" +
                            "                     technological_process_id\n" +
                            "              from operation_procedure\n" +
                            "              GROUP BY technological_process_id) as abc\n" +
                            "                 left join technological_process tp on abc.technological_process_id = tp.id\n" +
                            "        where tp.p_bom_no  = :p_bom_no \n" +
                            "          and tp.`status` = 1";
                    Map<String,Object> paramMap = new HashMap<>();
                    paramMap.put("p_bom_no",pBom);

                    Entity timeEntity= Db.use(dbGroup).queryOne(sql, paramMap);
                    if(timeEntity == null){
                        System.out.println("pbom:"+pBom+"没有对应的加工数据");
                        continue;
                    }
                    BigDecimal totalTime = timeEntity.getBigDecimal("totalTime");
                    BigDecimal jiaGongCount = timeEntity.getBigDecimal("jiaGongCount");
                    BigDecimal time = totalTime.multiply(new BigDecimal(totalQuantity).divide(new BigDecimal(60), 8, RoundingMode.DOWN).divide(jiaGongCount, 3, RoundingMode.DOWN));


                    /** 修改生产汇报单子  **/
                    PrdMorptSaveRequest request = new PrdMorptSaveRequest();
                    request.setIsDeleteEntry(false);

                    PrdMorptSaveRequest.Model model = new PrdMorptSaveRequest.Model();
                    model.setFID(id);
                    model.setFDate(date);

                    List<PrdMorptSaveRequest.FEntity> entities = new ArrayList<>();
                    PrdMorptSaveRequest.FEntity entity = new PrdMorptSaveRequest.FEntity();
                    entity.setFEntryID(fEntityId);
                    entity.setFQuaQty(totalQuantity);
                    entity.setFFinishQty(totalQuantity);
                    entity.setFHrWorkTime(time);
                    entities.add(entity);
                    model.setFEntity(entities);

                    request.setModel(model);

                    String requestJson = JSONUtil.toJsonStr(request);
                    System.out.println("请求参数：" + requestJson);
                    String saveResult = k3CloudApi.save("PRD_MORPT", JSONUtil.toJsonStr(requestJson));
                    System.out.println("保存结果：" + saveResult);
                }
            }
        }
    }

}
